package com.crack;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.instrument.Instrumentation;

/**
 * @date 2019/8/2
 */
public class CrackAgent {

    public static void premain(final String args, final Instrumentation inst) {
        System.out.println("========== enter permain ==========");
        String version = getVersion();
        if (version != null && version.length() > 0) {
            VersionEnum versionEnum;
            try {
                versionEnum = VersionEnum.valueOf("V" + version.replaceAll("\\.", "_"));
            } catch (Exception e) {
                e.printStackTrace();
                versionEnum = VersionEnum.DEFAULT;
//				return;
            }
            inst.addTransformer(new Agent(versionEnum));
        }
    }

    /**
     * 获取软件版本
     *
     * @return 20xx.x.x
     */
    private static String getVersion() {
        String version = null;
        try {
            File currentDir = new File(".");
            FilenameFilter filter = (dir, name) -> name.endsWith(".jar") && name.contains("data-man-mongodb");
            String[] files = currentDir.list(filter);
            assert files != null;
            System.out.println("主文件:" + files[0]);
            version = files[0].substring(files[0].lastIndexOf("-") + 1, files[0].lastIndexOf("."));
            System.out.println("版本:" + version);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

}
